/*
 * File name: WatermarkPreviewPanel.java
 * 
 * Description: the panel layout of watermark preview
 *
 * Author: Theobald_wu, contact with wuqizhi@tydtech.com
 * 
 * Date: 2014-6-26   
 * 
 * Copyright (C) 2014 TYD Technology Co.,Ltd.
 * 
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.freeme.cameraplugin.watermarkmode.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.freeme.camera.CameraPluginUtil;
import com.freeme.camera.ICameraExt;
import com.freeme.cameraplugin.watermarkmode.R;
import com.freeme.cameraplugin.watermarkmode.WatermarkMode;
import com.freeme.cameraplugin.watermarkmode.model.WatermarkItemInfo;
import com.freeme.cameraplugin.watermarkmode.model.WatermarkResouceId;
import com.freeme.elementscenter.agent.ECOfflineItemData;
import com.freeme.elementscenter.agent.ECOfflineUtil;

public class WatermarkPreviewPanel extends RelativeLayout implements OnClickListener {
    private static final String TAG = "[TYD_DEBUG]WatermarkPreviewPanel";
    private static final int PAGE_IND_FADE_OUT_DELAY = 2000;
    public static final int CMD_CAMERA_CLOSE_MODE = 0x010;
    private ViewPager mPager;
    private MyAdapter mAdapter;
    private TextView mIndicator;
    private View mGuide;
    private ArrayList<WatermarkItemInfo> mItemInfoList = new ArrayList<WatermarkItemInfo>();

    private static final String ACTION_FREENEFC = "freeme.intent.action.freeme.ec";

    private ICameraExt mCamera;
    private int mCurrentPageIndex; // one page is one group
    private int mTotalPageNums; // watermark groups
    private boolean mHorizontalOri;
    private WatermarkMode mWatermarkManager;
    private Context mContext;
    private LinearLayout mTitleStrip;
    private int mCurrTypeIndex = 0;
    private TextView mBtnModePop;
    private TextView mBtnModeBack;
    private boolean isPop = false;
    private LinearLayout mTextEcDownLoad;
    private LinearLayout mSettingBottom;
    private int mTitleWidth;

    private Runnable mPageIndFadeout = new Runnable() {
        @Override
        public void run() {
            CameraPluginUtil.fadeOut(mIndicator);
        }
    };
    private ImageButton mLeftButton;
    private ImageButton mRightButton;

    public WatermarkPreviewPanel(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        mTitleWidth = context.getResources().getDimensionPixelSize(R.dimen.title_width);
    }

    @Override
    protected void onFinishInflate() {
        mPager = (ViewPager) findViewById(R.id.page);
        mIndicator = (TextView) findViewById(R.id.page_ind);
        mGuide = findViewById(R.id.guide);
        mLeftButton = (ImageButton) findViewById(R.id.watermark_swith_left);
        mRightButton = (ImageButton) findViewById(R.id.watermark_swith_right);
        mTitleStrip = (LinearLayout) findViewById(R.id.titleStrip);
        mBtnModePop = (TextView) findViewById(R.id.mode_button_down);
        mBtnModeBack = (TextView) findViewById(R.id.mode_button);
        mTextEcDownLoad = (LinearLayout) findViewById(R.id.ec_download);
        mSettingBottom = (LinearLayout) findViewById(R.id.watermark_setting_button);
        mAdapter = new MyAdapter();
        mPager.setAdapter(mAdapter);

        mLeftButton.setOnClickListener(this);
        mRightButton.setOnClickListener(this);

        mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            private boolean mIsScrollEnd;

            @Override
            public void onPageSelected(int position) {
                Log.i(TAG, "onPageSelected position:" + position);
                if (position == mCurrentPageIndex || mTotalPageNums <= 1) {
                    return;
                }

                mCurrentPageIndex = position;
                updateIndicator();
                WatermarkItemInfo info = mItemInfoList.get(mCurrentPageIndex);
                final String id = String.valueOf(info.thumbnailId) + info.thumbnailUrl;
                mWatermarkManager.setCurrItemId(id);
                WatermarkPreviewPanel.this.post(new Runnable() {
                    @Override
                    public void run() {
                        mWatermarkManager.updateWatermark(id);
                    }
                });
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.i(TAG, "onPageScrollStateChanged(" + state + ")");

                if (ViewPager.SCROLL_STATE_DRAGGING == state) {
                    WatermarkPreviewPanel.this.removeCallbacks(mPageIndFadeout);
                    mIndicator.setVisibility(VISIBLE);
                } else if (ViewPager.SCROLL_STATE_IDLE == state) {
                    WatermarkPreviewPanel.this.removeCallbacks(mPageIndFadeout);
                    WatermarkPreviewPanel.this
                            .postDelayed(mPageIndFadeout, PAGE_IND_FADE_OUT_DELAY);

                    // pop up setting panel
                    if (mIsScrollEnd) {
                        // mCamera.getWatermarkManager().popupSettingPanel();
                    }
                }
            }

        });
        mTextEcDownLoad.setOnClickListener(this);
        mBtnModePop.setOnClickListener(this);
        mBtnModeBack.setOnClickListener(this);
        initTitleStrip();
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        mPager.setEnabled(enabled);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        boolean isHorizontalOri = false;
        if (r - l > b - t) {
            isHorizontalOri = true;
        }
        updateIndicatorPosition(isHorizontalOri);

        super.onLayout(changed, l, t, r, b);
    }

    public void init(ICameraExt camera, WatermarkMode manager) {
        mCamera = camera;
        mWatermarkManager = manager;
        mTotalPageNums = WatermarkResouceId.TYPE_ARRAY.length;
        mItemInfoList.clear();
        updatePages(mCurrTypeIndex);
        initTitleStrip();
        showSettingPanal();
    }

    public View getOutputPanel(int orientation) {
        View panel = null;
        View child = mAdapter.getPrimaryItem();
        if (child instanceof WatermarkPageView) {
            WatermarkPageView item = (WatermarkPageView) child;
            panel = item.getOutputPanel(orientation);
        }
        return panel;
    }

    public void hideGuide() {
        mGuide.setVisibility(GONE);
    }

    private void updateIndicator() {
        if (mTotalPageNums <= 1) {
            return;
        }

        mIndicator.setText((mCurrentPageIndex + 1) + " / " + mTotalPageNums);
    }

    private void updateIndicatorPosition(boolean isHorizontalOri) {
        if (mHorizontalOri == isHorizontalOri) {
            return;
        }

        mHorizontalOri = isHorizontalOri;
        mIndicator.setVisibility(View.GONE);
        MarginLayoutParams lp = (MarginLayoutParams) mIndicator.getLayoutParams();
        if (mHorizontalOri) {
            // 90 or 270
            lp.bottomMargin = getResources().getDimensionPixelSize(
                    R.dimen.watermark_page_ind_margin_b1);
        } else {
            lp.bottomMargin = getResources().getDimensionPixelSize(
                    R.dimen.watermark_page_ind_margin_b);
        }
        mIndicator.setLayoutParams(lp);
    }

    public class MyAdapter extends PagerAdapter {
        private View mCurrentView;

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            mCurrentView = (View) object;
        }

        public View getPrimaryItem() {
            return mCurrentView;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            WatermarkItemInfo itemInfo = mItemInfoList.get(position);
            WatermarkPageView item = new WatermarkPageView(mContext, mWatermarkManager, mCamera);
            item.setWatermarkItemInfo(itemInfo);
            container.addView(item);
            return item;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object obj) {
            container.removeView((View) obj);
        }

        @Override
        public int getCount() {
            return mTotalPageNums;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view == object);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.watermark_swith_left:
                changeToPrev();
                break;
            case R.id.watermark_swith_right:
                changeToNext();
                break;
            case R.id.mode_button_down:
                if (!isPop) {
                    showSettingPanal();
                } else {
                    hideSettingPanal();
                }
                break;
            case R.id.mode_button:
                switchNormalMode();
                break;
            case R.id.ec_download:
                try {
                    Intent intent = new Intent(ACTION_FREENEFC);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra(ECOfflineUtil.TYPE_CODE_TAG, ECOfflineUtil.WATERWARK_TYPE_CODE);
                    mCamera.getHostContext().startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(mContext, R.string.startup_ec_tip, Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void changeToPrev() {
        mPager.setCurrentItem(mCurrentPageIndex - 1, false);
        setChangeButtonEnable();
    }

    private void changeToNext() {
        mPager.setCurrentItem(mCurrentPageIndex + 1, false);
        setChangeButtonEnable();
    }

    private void switchNormalMode() {
        mCamera.sendCommand(CMD_CAMERA_CLOSE_MODE);
    }

    private void setChangeButtonEnable() {
        if (mCurrentPageIndex == 0) {
            mLeftButton.setEnabled(false);
        } else {
            mLeftButton.setEnabled(true);
        }

        if (mCurrentPageIndex == mItemInfoList.size() - 1) {
            mRightButton.setEnabled(false);
        } else {
            mRightButton.setEnabled(true);
        }
    }

    private void initTitleStrip() {
        final int pageCount = WatermarkResouceId.TYPE_ARRAY.length;
        final ColorStateList textColor = getResources().getColorStateList(
                R.drawable.stretch_list_item_text_color);
        final int textSize = getResources().getDimensionPixelSize(
                R.dimen.setting_page_title_text_size);

        mTitleStrip.removeAllViews();
        for (int i = 0; i < pageCount; i++) {
            // modify by TYD mingjun for new img
            LayoutInflater mInflater = LayoutInflater.from(getContext());
            View view = mInflater.inflate(R.layout.setting_item, mTitleStrip, false);
            RotataTextView title = (RotataTextView) view.findViewById(R.id.text);
            ImageView icon = (ImageView) view.findViewById(R.id.icon);
            if (getState(i) && mCurrTypeIndex != i) {
                icon.setVisibility(View.VISIBLE);
            } else {
                icon.setVisibility(View.GONE);
            }
            // end
            String type = WatermarkResouceId.TYPE_ARRAY[i];
            int StringId = WatermarkResouceId.TYPE_STRING_ID.get(type);
            title.setText(StringId);
            title.setTextColor(textColor);
            title.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            title.setGravity(Gravity.CENTER);

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mTitleWidth,
                    LinearLayout.LayoutParams.MATCH_PARENT, 1f);
            mTitleStrip.addView(view, lp);

            view.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    int index = mTitleStrip.indexOfChild(v);
                    // mPager.setCurrentItem(index);
                    if (index != mCurrTypeIndex) {
                        mTitleStrip.getChildAt(mCurrTypeIndex).setSelected(false);
                        mTitleStrip.getChildAt(index).setSelected(true);
                        mCurrTypeIndex = index;
                    }
                    ImageView icon = (ImageView) v.findViewById(R.id.icon);
                    icon.setVisibility(GONE);
                    updatePages(index);
                    clearnState(index);
                }
            });
        }
        mTitleStrip.getChildAt(mCurrTypeIndex).setSelected(true);
    }

    public void updatePages(int type_index) {
        mItemInfoList.clear();
        String type = WatermarkResouceId.TYPE_ARRAY[type_index];
        List<String> tags = WatermarkResouceId.PAGE_ARRAY_TAG.get(type);
        for (String tag : tags) {
            WatermarkItemInfo itemInfo = WatermarkResouceId.ITEM_RESOURCE_IDS.get(tag);
            itemInfo.setType(type);
            mItemInfoList.add(itemInfo);
        }

        List<ECOfflineItemData> itemList = ECOfflineUtil.getOfflineItemDataByType(
                ECOfflineUtil.WATERWARK_TYPE_CODE, type_index);
        for (ECOfflineItemData dynmicItem : itemList) {
            int layoutId = WatermarkResouceId.TYPE_LAYOUT_ID.get(type);
            WatermarkItemInfo itemInfo = new WatermarkItemInfo(layoutId, dynmicItem.mColor,
                    dynmicItem.mThumbnailUrl, dynmicItem.mPrimitiveUrl, dynmicItem.mPrompt,
                    dynmicItem.mName);
            itemInfo.setType(type);
            if (ECOfflineUtil.isFileExist(dynmicItem.mItemNewStatusFileFullName)) {
                mItemInfoList.add(0, itemInfo);
            } else {
                mItemInfoList.add(itemInfo);
            }
        }

        mTotalPageNums = mItemInfoList.size();
        mAdapter.notifyDataSetChanged();
        mCurrentPageIndex = 0;
        mPager.setCurrentItem(mCurrentPageIndex);
        updateIndicator();
        setChangeButtonEnable();
    }

    public void hideSettingPanal() {
        Drawable drawble = mContext.getResources().getDrawable(R.drawable.mode_setting_pop_up);
        drawble.setBounds(0, 0, drawble.getIntrinsicWidth(), drawble.getIntrinsicHeight());
        mBtnModePop.setCompoundDrawables(null, null, drawble, null);
        mSettingBottom.setVisibility(View.GONE);
        isPop = false;
    }

    public void showSettingPanal() {
        Drawable drawble = mContext.getResources().getDrawable(R.drawable.mode_setting_pop_down);
        drawble.setBounds(0, 0, drawble.getIntrinsicWidth(), drawble.getIntrinsicHeight());
        mBtnModePop.setCompoundDrawables(null, null, drawble, null);
        Log.i(TAG, "showSettingPanal");
        mSettingBottom.setVisibility(View.VISIBLE);
        isPop = true;
    }

    // modify by TYD mingjun for new img
    public boolean getState(int type_index) {
        boolean state = false;
        List<ECOfflineItemData> itemList = ECOfflineUtil.getOfflineItemDataByType(
                ECOfflineUtil.WATERWARK_TYPE_CODE, type_index);
        for (ECOfflineItemData dynmicItem : itemList) {
            if (ECOfflineUtil.isFileExist(dynmicItem.mItemNewStatusFileFullName)) {
                state = true;
            }

        }
        return state;
    }

    public void clearnState(int type_index) {
        List<ECOfflineItemData> itemList = ECOfflineUtil.getOfflineItemDataByType(
                ECOfflineUtil.WATERWARK_TYPE_CODE, type_index);
        for (ECOfflineItemData dynmicItem : itemList) {
            if (ECOfflineUtil.isFileExist(dynmicItem.mItemNewStatusFileFullName)) {
                ECOfflineUtil.deleteFile(dynmicItem.mItemNewStatusFileFullName);
            }
        }
    }
    // end
}
